var db;
var lessonID = getUrlVars()["leid"];
var readingLessonIDSelected = getLocalStorage('readingLessonIDSelected');

if (lessonID == null) {
	if (readingLessonIDSelected == null) { ////Lan chay dau tien : khong co lessonID va lessonForwardSelected -->load nhung bai doc cua lesson dau tien (mac dinh coi la 1)
		lessonID = 1;
		setLocalStorage('readingLessonIDSelected',lessonID);
	}else{ //ko phai lan chay dau tien(nhung cung khong co lessonID tren url) -> lay lessonForwardSelected dc luu trong localStorage
		lessonID = readingLessonIDSelected
	}
}else {// lay chay sau, co lessonID tren url -> cap nhat lai lessonForwardSelected
	setLocalStorage('readingLessonIDSelected',lessonID);
}


function connectDB() {
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(getReadingListByLesson, errorCB);
}


// function will be called when an error occurred
function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

function successCB() {
	db.transaction(getReadingListByLesson, errorCB);
}

function getReadingListByLesson(tx) {
	var sql = "SELECT r_id, r_title, r_lesson_id, le_id, le_title "
			+ " FROM reading " 
			+ " INNER JOIN lesson"
			+ " ON reading.r_lesson_id = lesson.le_id"
			+ " WHERE reading.r_lesson_id =  " + lessonID 
			+ " ORDER BY r_id ASC ";
	tx.executeSql(sql, [], showReadingListByLesson);
}


function showReadingListByLesson(tx, results) {
	//show title
	getLessonTitle(lessonID).done(function(title) { 
	    $('#lesson-name').append(title);
	});

	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#reading-list').append('<li class="ui-first-child"><a href="reading_detail.html?leid=' + data.r_lesson_id + '&id='
									+ data.r_id
									+ '" data-ajax="false" data-direction="reverse" class="ui-btn ui-btn-icon-right ui-icon-carat-r" style="font-weight:normal;font-family:Times New Roman, Times, serif;"> '
									+ data.r_title + '</a></li>');
		}
	}else{
		$('#reading-list').append('<div style="margin: 20px; 20px;">Updating...</div>');
	}
}
